import { OnInit, Component } from '@angular/core';
import { EurekaRegisterService } from 'src/app/services/eureka-manage/eureka-register.service';
import { Eureka } from 'src/app/entity/eureka-manage/eureka';
import { UUIDUtils } from 'src/app/utils/uuid-utils';
import { LineEditFormCache as LineEditCache } from 'src/app/entity/common/line-edit-cache';
import { FormControl, Validators } from '@angular/forms';

@Component({
    selector: 'app-register',
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.less']
  })
export class RegisterComponent implements OnInit {

  eurekaList: Eureka[];
  lineEditCaches: Map<string, LineEditCache>;

  constructor(private eurekaRegisterService: EurekaRegisterService) { }

    ngOnInit() {
      this.fetchData();
      this.lineEditCaches = new Map<string, LineEditCache>();
    }

    fetchData = () => {
      this.eurekaRegisterService.getAllEureka().subscribe(data => this.eurekaList = data);
    }

    addLine = () => {
      const newLine = new Eureka();
      const cache = LineEditCache.create({
        record: new Eureka()
      });
      newLine.code = cache.id;
      this.lineEditCaches.set(cache.id + '', cache);
      this.eurekaList.push(newLine);
    }

    deleteEureka = (record: Eureka) => {
      this.eurekaRegisterService.deleteEureka(record.code).subscribe(
        data => this.fetchData()
      );
    }

    cancelEditLine = (record: Eureka) => {
      const cache = this.lineEditCaches.get(record.code);
      this.lineEditCaches.delete(record.code);
      if (cache.status === 'new') {
        this.removeItemFromTableById(record.code);
      }
    }

    saveEditLine = (record: Eureka) => {
      const cache = this.lineEditCaches.get(record.code);
      if (!cache.record.code || !cache.record.address) {
        return;
      }
      this.eurekaRegisterService.createEureka(cache.record)
        .subscribe(data => {
          this.lineEditCaches.delete(cache.id);
          this.fetchData();
        });
    }

    removeItemFromTableById = (id: string) => {
      this.eurekaList = this.eurekaList.filter((value: Eureka) => value.code !== id);
    }

    isEditing = (id: string) => {
      return !!this.lineEditCaches.get(id);
    }

    isEditCacheEmpty = () => {
      return !this.lineEditCaches || this.lineEditCaches.size === 0;
    }

}
